/**
 * 登录页面逻辑处理
 */

import {list} from '../../../js/modules/mall';
import * as account from '../../../js/modules/account.js'
import authorize from '../../../js/modules/authorize.js'
import {config,domain} from '../../../js/modules/gloab';
import {
  api,storage,dialog, util,forms
} from '../../../js/util'
import {
  pagesInfo,
  router
} from '../../../js/router'
import BasePage from '../../../js/common/base-page'
import { jsonToQuery } from '../../../js/newUtil';
import { setStorageSync } from '../../../js/compatible';
const info = require("../../../js/modules/info.js");
var app = getApp();
BasePage({
  pageKey: "login",
  validateLogin:false,
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    role: "store", // 当前页面登录角色
    wxRegisterAndLogin:true,//微信是否登录
    // 登录后供应商信息
    supplier: {
      "display": "none", // 多供应商列表显示
      "list": [] // 待选供应商列表
    },
    forms: {
      UserName: {
        value: "", //
        validate: "isnull",
        error: "请输入正确的手机号"
      },
      Password: {
        value: "", //
        validate: "isnull",
        error: "请输入正确的密码"
      },
      IsAgree:{
        value: false,
        fixed: true,
        validate: "isnull",
        error: "请阅读并同意服务协议和隐私政策"
      }
    },
    smsForm:{
      code:{
        value:'',
        validate:"isnull",
        error:"请输入手机验证码"
      }
    },
    logo: "",
    bg_pic: "",
    totleHeight: '603px',
    timer: null,
    enableJoin: true,
    isParsed: false,
    loopCount: 0, //循环数量
    logoHeight:80,
    shadowTitle:'服务协议',
    smsValidate:false,        //短信验证模式
    isLoginVisit:false,
    mainColor:'',//主题色
    pathUrl:'',
    version:'',//版本 一代还是二代
    loginType:0,//登录方式
    msg: "获取验证码",
    notifyTime: 60,
    isSendSmsCode: false, //是否已发送短信校验码
    proprietorVersion: 0,
    managerNotLogin: false //是否显示内部员工入口
  },
  /**
   * 表单输入框值绑定
   */
  bindFormValue: function(e) {
    e = e.detail;
    this.data.forms[e.target.id].value = e.detail.value;

  },
  bindSmsFormValue:function(e){
    e = e.detail;
    this.data.smsForm.code.value = e.detail.value;
  },

  /**
   * 注册
   */
  bindRegister:function(){
    router.redirect({
      path:'register',
      params:{
        role: this.data.role,
        type:encodeURIComponent(this.data.pathUrl)
      }
    })
  },
  
  /**绑定用户信息 */
  onBindUserInfo: function(e) {
    var that = this;
    if (that.data.isExcuting) return;
    if (e.detail.errMsg.indexOf("fail auth deny") > -1 || e.detail.userInfo == undefined) {
      this.verifylogin(e);
      return;
    }
    if (!this.data.forms.IsAgree.value) {
      util.alert("请阅读并同意服务协议和隐私政策");
      return;
    }
    that.setData({
      isExcuting: true
    });
    var userInfo = {};
    userInfo["code"]=that.data.code;
    userInfo["iv"]=e.detail.iv;
    userInfo["encryptedData"]=e.detail.encryptedData;
    account.login.saveAuthInfo(that.data.role, userInfo, function(res) {
      //跳转
      router.redirect({
        path: "phoneauth",
        params:{
          role: that.data.role,
          WxUserId:res.WxUserId,
          OfficialUserId:res.OfficialUserId,
          unionId:res.unionId,
        }
      });
    }, (bo, token, virtualPath) => {
      this.success(bo, token, virtualPath);
      that.setData({
        isExcuting: false
      });
    });
  },
  /*
   *登录校验 
   */
  verifylogin: function(e) {
    // console.log(e)
    var that = this;
    if (that.data.isExcuting) return;
    that.setData({
      isExcuting: true
    });
    app.getOpenId('',function(contet){
      if(!contet.Success){
        util.tips(contet.Message);
        that.setData({
          isExcuting: false
        });
        return
      }
      setStorageSync('openid', contet.Content.openid)
      // console.log(that.data.forms,'-=-=-=-');
      account.login.verifylogin(that.data.role, that.data.forms,that.data.loginType,function(res) {
        //展示弹出层
        that.setData({ 
          supplier: {
            "display": 'block',
            list: res.Content,
            isExcuting: false
          }
        });

      }, (bo, token, virtualPath) => {
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });
      },(res)=>{
        console.log(res,'======');
        that.needSmsValidate(res.Content[0].Token,res.Content[0].Id);
      });
    })
  },
  /*需要跳转验证短信*/
  needSmsValidate:function(token,id){
    let that = this;
    util.tips("请先验证短信");
    that.setData({
      smsValidate:true,
      isExcuting: false,
      loginToken:token,   //暂存的登录token
      loginId:id,        //暂存的登录主体
      supplier:{
        "display":'none'
      }
    },()=>{
      //获得发送短信组件
      that.smsVerifyCode = that.selectComponent("#smsVerifyCode");
      //设置回调
      that.smsVerifyCode.data.callback = that.bindSmsVerifyCode;
    })
  },
  /**微信一键授权登录 */
  onBindPhone: function(e) {
    // console.log(e,'=========',this.data.isExcuting);
    var that = this;
    if (that.data.isExcuting) return;
    if (e.detail.errMsg.indexOf("getPhoneNumber:ok") == -1) {
      console.log(e.detail,'=====提示')
      return;
    }
    if (!this.data.forms.IsAgree.value) {
      util.alert("请阅读并同意服务协议和隐私政策");
      return;
    }
    that.setData({
      isExcuting: true
    });
    var userInfo =e.detail || {};   
    let qr = that.data.qr || ''
    if (!/_0$/.test(qr)) {
      userInfo["qr"]=that.data.qr;
    }
    userInfo["code"]=that.data.code;
    app.getOpenId('',function(contet){
      if(!contet.Success){
        util.tips(contet.Message);
        that.setData({
          isExcuting: false
        });
        return
      }
      var content = contet.Content || {};
      userInfo["openid"]=content.openid;
      userInfo["unionid"]=content.unionid;
      account.login.onAuthLoginVerify(that.data.role, userInfo,function(res) {
        //展示弹出层
        that.setData({
          supplier: {
            "display": 'block',
            list: res.Content,
            isExcuting: false
          }
        });
      }, (bo, token, virtualPath) => {
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });

      }, that);
    })
  },
  bindBackHome:function(){
    setStorageSync('tabindex', -1);
    router.switchTab({
      path: "index", 
    });
  },
  /*返回登录 */
  bindBackLogin:function(){
    this.setData({
      smsValidate:false
    })
  },
  /*选择商家登录 */
  select_login: function(e) {
    var that = this;
    var res = e.currentTarget.dataset.res;
    if(that.data.role=='store' && res.LoginSmsValidate){
      that.needSmsValidate(res.Token,res.Id);
    }else{
      account.login.login(that.data.role, res.Token, (bo, token, virtualPath)=> {
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });
      });
    }
  },
  /**登录成功后 */
  success(bo, token, virtualDir) {
    var that = this;
    let data = util.getBeforeLoginData()
    util.removeCategoryCache()
    if (bo) {
      let role=authorize.loginRole();
      var entity = authorize.getEntity();
      if(role=="store"){
        app.getOpenId(entity.manager.Token || '');
        if(that.data.pathUrl){
          let backUrl = that.data.backUrl||"";
          backUrl = backUrl == "undefined" ? "" : backUrl;
          router.redirect({
              path: "packageStore/pages/product/detail/detail"+that.data.pathUrl,
              params: {
                action: "skip",
                token: token,
                role: role,
                hashPath: backUrl
              }
            });
        } else if (data.route) {
          this.reback(data)
        } else{
          that.bindBackHome();
        }
      }else{
        let backUrl = that.data.backUrl||"";
        backUrl = backUrl == "undefined" ? "" : backUrl;
        backUrl=(role=="vendor"?"#/vendor/admin":role=="supplier"?"#/supplier/admin":"#/clerk");
        router.redirect({
          path: "interim",
          params: {
            action: "skip",
            token: token,
            role: role,
            hashPath: backUrl
          }
        });
      }
    } else if(token==40029){
      wx.login({
        success: res =>{
          that.data.code = res.code
        }
      });
    }
  },
  /**
   * 返回登录前页面/跳转到指定页面
   * @param {*} data 
   */
  reback (data = {}) {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    if (!prevPage) {
      prevPage = {}
    }
    if (prevPage.route == data.route && jsonToQuery(prevPage.options) == data.options) {
      prevPage.onLoad()
      prevPage.onshow()
      wx.navigateBack()
    } else {
      wx.redirectTo({
        url: `/${data.route}?${data.options}`,
        fail () {
          wx.switchTab({
            url: `/${data.route}`,
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    var role = "store",
        scene = storage.get('scene')||'1_0_0';
    if (options.role) {
      role = options.role;
    }else{
      role=authorize.loginRole();
    }
    this.data.role=role;
    this.setData({
      role:role,
      qr:scene,
      isLoginVisit:api.isLoginVisit,
      pathUrl:decodeURIComponent(options.type || '')
    });
    this.data.backUrl = decodeURIComponent(options.backUrl) || "";

    //完善信息后直接登录
    if (options.token && options.token != '') {
      account.login.login(role,options.token,(bo, token, virtualPath) => {
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });
      })
    }

    if (options.logout) {
      //退出登录
      authorize.loginOut();
      if (app.dns.proprietor != app.dns.fkFlag) {
        app.dns.proprietorId = 0;
      }
    }
    //判断是否登录
    else if (authorize.isLogin(this.data.role)) {
      let entity = authorize.getEntity(this.data.role);
      this.success(true, entity.manager.Token)
    }
    if (app.dns.fkId == 0) {
      this.check_dns_analysis(this);
    } else {
      this.setData({
        isParsed: true
      });
    }
    this.get_website_config();
    var username = "",password = "";
    if (options.userName && options.password) {
      username = options.userName;
      password = options.password;
    }

    //注册后模拟登录
    if (username.length > 0 && password.length > 0) {
      this.data.forms.UserName.value = username;
      this.data.forms.Password.value = password;
      this.data.forms.IsAgree = true
      this.verifylogin();
      this.setData({
        forms: this.data.forms
      });
    }
    wx.login({
      success: res =>{
          this.data.code = res.code
      }
    });
    //计算协议高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          totleHeight: res.windowHeight + 'px'
        });
      }
    });
  },
  /**
   * 获取服务协议
   */
  getProtocol:function(){
    let that = this;
    account.register.getProtocol(this.data.role,function(res){
      let content;
      if(app.dns.proprietor == app.dns.fkFlag){
        content = res
      }else{
        content = res.Content.JoinProtocol;//.replace(/<br\s*\/?>/gi, "\n").replace(/(^\s*)|(\s*$)/g, "\t");
      }
      that.setData({
        shadowTitle:'服务协议',
        richtext_content: content
      })
      that.showModal();
    })
  },
  /**
   * 获取隐私政策
   */
  getPrivacy:function(){
    let that = this;
    account.register.getPrivacy(function(res){
      that.setData({
        shadowTitle:'隐私政策',
        richtext_content: res
      },()=>{
        that.showModal();
      })
    })
  },
  /**
   * 检测dns和分析
   */
  check_dns_analysis: function(that) {
    that.data.timer = setInterval(function() {
      if (app.dns.fkId > 0) {
        that.setData({
          isParsed: true,
          independentPackage: app.dns.proprietorId > 0
        });
        clearInterval(that.data.timer);
      }
      if (that.data.loopCount > 60) {
        clearInterval(that.data.timer);
        that.data.loopCount = 0;
      }
    }, 100);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setNavigationBarTitle({
      title: api.title
    });

  },
  /**是否同意服务条款 */
  checkboxChange(e) {
    if (this.data.forms.IsAgree.value) {
      this.data.forms.IsAgree.value = false;
    } else {
      this.data.forms.IsAgree.value = true;
    }
    this.setData({ forms: this.data.forms });
  },
  /**加载站点信息 */
  get_website_config() {
    var that = this;
    let {
      logo,bg_pic,imgDomain
    } = this.data;
    if (app.dns.proprietorId != app.dns.fkId) return;
    that.setData({
      logo: api.webSite.logo.length > 0 ? api.webSite.logo : logo,
      bg_pic: api.webSite.bgPic.length > 0 ? api.webSite.bgPic : bg_pic,
    });
  },
  /**logo自定义 */
  logoLoad(e){
    if(this.data.logo=='') return;
    var imgwidth = e.detail.width,
        imgheight = e.detail.height;
    var logoHeight = 440*imgheight/imgwidth;
    this.setData({
      logoHeight:logoHeight>200?200:logoHeight
    })
  },
  /**获得配置 */
  getconfigs: function() {
    var that = this;
    config.getProprietor(function(res) {
      if (res && res.Success) {
        let datas = res.Content || [];
        if (datas&&datas.length>0) {
          let item = datas[0];
          that.setData({
            proprietorVersion: item.ProprietorVersion || 0
          });
        }
      }
    });
    config.getConfig(
      app.dns.proprietorId,
      app.dns.proprietor,
      'Roles',
      'StoreSetting',
      function(res) {
        if (res && res.Success) {
          var content = res.Content;
          var wxRegisterAndLogin = content.WXRegisterAndLogin;
          if(that.data.loginType == 1){
            that.data.forms.Password.error = '请输入验证码';
          }
          that.setData({
            wxRegisterAndLogin: wxRegisterAndLogin,
            enableJoin: content.EnableJoin,
            loginType: content.LoginType || 0
          });
        }
      });
    config.getWholesaleConfigs(
      app.dns.proprietorId,
      app.dns.proprietor,
      "Wholesale",
      function(model) {
        that.setData({
          managerNotLogin: model.ManagerNotLogin == true
        });
      }
    );
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      independentPackage: app.dns.proprietorId > 0,
      mainColor:api.titleColor||"#e56b14"
    });
    this.getconfigs();
    this.getVersion();

  },
  /**
   * 登录角色切换
   */
  changeRole:function(e){
    var role = e.currentTarget.dataset.role;
    this.setData({
      role:role
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 显示遮罩层
   */
  showModal: function (evt) {
    dialog.showModal(this, 'showModalStatus')
  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**获取短信验证码 */
  bindSmsVerifyCode:function(callback){
    let data = {
      ProprietorId:app.dns.proprietorId,
      mobile:this.data.forms.UserName.value
    };
    console.log(this.data.forms.UserName.value,'0000000000');
    info.sms.getSmsVerifyCode(data, "info.login.send", function (content) {
      if (callback && typeof (callback) == "function") {
        callback(content);
      }
    });
  },
  /**验证短信 */
  bindVerifySms:function(){
    let that = this;
    var bo = forms.formValidate(that.data.smsForm);
    if (!bo) return;
    let param = {
      ProprietorId:that.data.loginId,
      mobile:that.data.forms.UserName.value,
      code:that.data.smsForm.code.value
    };
    account.login.smsValidate(param,function(){
      account.login.login(that.data.role, that.data.loginToken, (bo, token, virtualPath)=> {
        that.success(bo, token, virtualPath);
        that.setData({
          isExcuting: false
        });
      });
    })
  },
  getVersion(){
    var that = this;
    domain.getDomain((res)=> {
      if (res && res.Success) {
        let item = res.Content;
        if (item) {
          storage.put("version", Number(item.SoftwareVersion) || 1);
          that.setData({
            version:Number(item.SoftwareVersion) || 1
          })
        }
      }
    });
  },
  bindInputEvent(e){
    let forms = this.data.forms
    forms.Password.value = e.detail.value
    this.setData({
      forms
    })
  },
  bindSmsVerifyCodes(callback){
    var that =this;
    if (that.data.isSendSmsCode) return;
    if(!this.data.forms.UserName.value){
      util.tips('请输入手机号');
      return;
    }
    let data = {
      ProprietorId:app.dns.proprietorId,
      mobile:this.data.forms.UserName.value
    };
    console.log(this.data.forms.UserName.value,'0000000000');
    info.sms.getSmsVerifyCode(data, "info.login.send", function (content) {
      that.setData({
        isSendSmsCode: true,
        notifyTime: 60,
        msg: "60S"
      });
      that.decTime();
    });
  },
  /*倒计时*/
  decTime: function() {
    var that = this;
    var notifyTime = that.data.notifyTime - 1;
    that.setData({
      notifyTime: notifyTime,
      msg: notifyTime + "s后重新获取"
    });
    if (notifyTime > 0) {
      setTimeout(function() {
        that.decTime();
      }, 1000)
    } else {
      that.setData({
        isSendSmsCode: false,
        msg: "获取验证码"
      });
    }
  },
});